package org.grayrabbit.cms.content.imp;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.grayrabbit.cms.content.base.Common;
import org.grayrabbit.cms.content.base.DocElement;
import org.grayrabbit.cms.entity.Category;
import org.grayrabbit.cms.entity.Content;
import org.grayrabbit.cms.entity.FlashContent;
import org.grayrabbit.cms.entity.LinkContent;
import org.grayrabbit.cms.entity.PictureContent;
import org.grayrabbit.cms.entity.SoftwareContent;
import org.grayrabbit.cms.entity.VideoContent;
import org.grayrabbit.cms.util.DateUtil;
import org.grayrabbit.cms.util.FileUtil;
import org.grayrabbit.cms.util.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 *		ImportContent.java
 *		@Author      hasau   
 *		@CreateTime  2012-2-3  下午2:50:41	
 **/
public class ContentImport extends Common{
	private static final Logger LOGGER =LoggerFactory.getLogger(ContentImport.class);
	
	
	/**
	 * @param file 单个的xml文件
	 * @param categoryId 
	 * @param suffix 
	 * @param categoryId 
	 * @param siteId 
	 * @return 成功导入的数量{10,8} 总计10个内容成功导入8个
	 */
	public static Content singleXMLImport(File file, String categoryId, String siteId){
		return handleXML(file,categoryId,siteId);
	}
	
	public static Content zipXMLImport(File file, String categoryId, String siteId){
		//TODO  zip xml 处理
		return handleXML(file,categoryId,siteId);
	}
	
	/**
	 * @param zipFile zip压缩包
	 * @param unZipFileName  zip解压后的文件夹路径
	 * @return 成功导入的数量{10,8} 总计10个内容成功导入8个
	 * @throws IOException 
	 * @throws IllegalArgumentException 
	 */
	public static List<String> zipExtract(File zipFile, String unZipFileName)
			throws IllegalArgumentException, IOException {
		ZipUtil.extractZip(zipFile.getAbsolutePath(),
				unZipFileName, "GBK", new String[] {Common.XML}, BUFFER_SIZE); 
		File file = new File(unZipFileName);
		List<String> list = null ;
		if(file.exists() && file.isDirectory()){
			zipFile.delete();
			list  = new ArrayList<String>();
			FileUtil.loadFilePath(file, list);
			return list;
		}else{
			return null;
		}
	}

	private static Content handleXML(File file, String categoryId, String siteId) {
		try {
			SAXReader reader = new SAXReader();
			Document doc = reader.read(file);
			Element root = doc.getRootElement();
			String type = root.attribute(DocElement.CONTEXT_TYPE).getValue();
			@SuppressWarnings("unchecked")
			List<Element> list = root.elements();
			String name = null;
			String text = null;
			if (DocElement.CONTENT.equals(type)) {
				Content content = new Content();
				content.setSiteId(siteId);
				loadCommomLoop(list, name, text, content);
				setCategory(categoryId, content);
				return content;
			} else if (DocElement.PICTURE.equals(type)) {
				PictureContent content = new PictureContent();
				content.setSiteId(siteId);
				loadCommomLoop(list, name, text, content);
				setCategory(categoryId, content);
				return content;
			} else if (DocElement.SOFT.equals(type)) {
				SoftwareContent content = new SoftwareContent();
				content.setSiteId(siteId);
				loadSoftLoop(list, name, text, content);
				setCategory(categoryId, content);
				return content;
			} else if (DocElement.VIDEO.equals(type)) {
				VideoContent content = new VideoContent();
				content.setSiteId(siteId);
				loadVideoLoop(list,name,text,content);
				setCategory(categoryId, content);
				return content;
			} else if (DocElement.FLASH.equals(type)) {
				FlashContent content = new FlashContent();
				content.setSiteId(siteId);
				loadVideoLoop(list,name,text,content);
				setCategory(categoryId, content);
				return content;
			} else if (DocElement.LINK.equals(type)) {
				LinkContent content = new LinkContent();
				content.setSiteId(siteId);
				loadLinkLoop(list,name,text,content);	
				setCategory(categoryId, content);
				return content;
			} else {
				return null;
			} 
		} catch (Exception e) {
			LOGGER.error("解析XML文档异常", e);
			return null;
		}
	}
	
	private static void loadLinkLoop(List<Element> list, String name,
			String text, LinkContent content) {
		for (Element e : list) {
			name = e.getName();
			text = e.getTextTrim();
			loadAttr(content, name, text);
			if (DocElement.LINK_URL.equalsIgnoreCase(name)) {
				content.setLinkUrl(text);
			}
		} 
	}

	/**
	 * @param list  xml元素集合
	 * @param name  标签
	 * @param text  值
	 * @param content  内容
	 */
	private static void loadSoftLoop(List<Element> list, String name,
			String text, SoftwareContent content) {
		for (Element e : list) {
			name = e.getName();
			text = e.getTextTrim();
			loadAttr(content, name, text);

			if (DocElement.SOFTWARE_AUTH.equalsIgnoreCase(name)) {
				content.setSoftwareAuth(text);
			}
			if (DocElement.SOFTWARE_ENV.equalsIgnoreCase(name)) {
				content.setSoftwareEnv(text);
			}
			if (DocElement.SOFTWARE_LANGUAGE.equalsIgnoreCase(name)) {
				content.setSoftwareLanguage(text);
			}
			if (DocElement.SOFTWARE_LEVEL.equalsIgnoreCase(name)) {
				content.setSoftwareLevel(text);
			}
			if (DocElement.SOFTWARE_PIC.equalsIgnoreCase(name)) {
				content.setSoftwarePic(text);
			}
			if (DocElement.SOFTWARE_SCORE.equalsIgnoreCase(name)) {
				if(StringUtils.isBlank(text)) text = "0";
				content.setSoftwareScore(Integer.parseInt(text));
			}
			if (DocElement.SOFTWARE_TYPE.equalsIgnoreCase(name)) {
				content.setSoftwareType(text);
			}
		}
	}
	
	/**
	 * @param list  xml元素集合
	 * @param name  标签
	 * @param text  值
	 * @param content  内容
	 */
	private static void loadVideoLoop(List<Element> list, String name,
			String text, VideoContent content) {
		for (Element e : list) {
			name = e.getName();
			text = e.getTextTrim();
			loadAttr(content, name, text);
			videoLoadAttr(content, name, text);
		}
	} 

	/**
	 * @param list  xml元素集合
	 * @param name  标签
	 * @param text  值
	 * @param content  内容
	 */
	private static void loadCommomLoop(List<Element> list, String name,
			String text, Content content) {
		for (Element e : list) {
			name = e.getName();
			text = e.getTextTrim();
			loadAttr(content, name, text);
		}
	}
    private static void loadAttr(Content content ,String name,String text){
    	if(DocElement.CONTENT_ID.equalsIgnoreCase(name)){
			if(StringUtils.isBlank(text)){
				content.setContentId(null);
			}else{
				content.setContentId(null);
				//TODO  id 问题 处理
			} 
		 }
		 if(DocElement.CONTENT_TITLE.equalsIgnoreCase(name)){
			 content.setContentTitle(text);
		 }
		 if(DocElement.SIMPLE_TITLE_1.equalsIgnoreCase(name)){
			 content.setSimpleTitle1(text);
		 }
		 if(DocElement.SIMPLE_TITLE_2.equalsIgnoreCase(name)){
			 content.setSimpleTitle2(text);
		 }
		 if(DocElement.SIMPLE_TITLE_3.equalsIgnoreCase(name)){
			 content.setSimpleTitle3(text);
		 }
		 if(DocElement.CONTENT_AUTHOR.equalsIgnoreCase(name)){
			 content.setContentAuthor(text);
		 }
		 if(DocElement.CONTENT_SOURCE.equalsIgnoreCase(name)){
			 content.setContentSource(text);
		 }
		 if(DocElement.KEYWORDS.equalsIgnoreCase(name)){
			 content.setKeywords(text);
		 }
		 if(DocElement.CONTENT_CONTEXT.equalsIgnoreCase(name)){
			 content.setContentContext(text);
		 }
		 if(DocElement.CONTENT_DESCRIPTION.equalsIgnoreCase(name)){
			 content.setContentDescription(text);
		 }
		 if(DocElement.CREATETIME.equalsIgnoreCase(name)){
			 content.setCreateTime(DateUtil.formatStringToDate(text, "yyyy-MM-dd HH:mm:ss"));
		 }
    }
    
    private static void videoLoadAttr(VideoContent content ,String name,String text){
    	if(DocElement.VIDEO_COPYRIGHT.equalsIgnoreCase(name)){
			 content.setVideoCopyright(text);
		}
    	if(DocElement.VIDEO_SOCER.equalsIgnoreCase(name)){
    		if(StringUtils.isBlank(text)) text = "0";
			 content.setVideoSocer(Integer.parseInt(text));
		}
    	if(DocElement.VIDEO_TAGS.equalsIgnoreCase(name)){
			 content.setVideoTags(text);
		}
    	if(DocElement.VIDEO_TYPE.equalsIgnoreCase(name)){
			 content.setVideoType(text);
		}
    	if(DocElement.VIDEO_YEAR.equalsIgnoreCase(name)){
    		content.setVideoYear(DateUtil.formatStringToDate(text, "yyyy-MM-dd"));
		}
    }
    
    private static void setCategory(String categoryId ,Content content){
    	Category c = new Category();
    	c.setCategoryId(categoryId);
    	content.setCategory(c); 
    }
}
